<?php

$adminEmail = $_POST['admin_email'];
$adminPassword = $_POST['admin_password'];
$verifyCode = $_POST['verify_code']; //
$rememberMe = $_POST['remember_me'] ?? '';

session_start();
if ($verifyCode != $_SESSION['verify_code']) {
    echo "验证码错误。<a href='index.php?c=login'>返回登录页</a>";
    exit();
}

include_once APP_PATH . "./model/login_check.php";

if (!$admin) {
    echo "账户或者密码不匹配。<a href='index.php?c=login'>返回登录页</a>";
    exit();
}

//$salt = "0w37qVYCCu#SV7s4x3ctMNwQS@&4Hc";
//$adminPassword = md5($salt. md5($salt . $adminPassword . $salt) . $salt);

if ($admin['admin_password'] == $adminPassword) {
    if (!session_id()) {
        session_start();
    }
    $_SESSION['admin_email'] = $adminEmail;
    $_SESSION['admin_name'] = $admin['admin_name'];
    if ($rememberMe) {
        setcookie('PHPSESSID', session_id(), time() + 20);
    }

    $log = [
        'action' => 'admin_login',
        'content' => '登录后台成功',
        'time' => date("Y-m-d H:i:s", time()),
        'ip' => $_SERVER['REMOTE_ADDR'],
        'admin_email' => $adminEmail,
    ];
    $file = fopen("./logs/" . date("Y-m-d") . ".txt", 'a+');
    if ($file) {
        fwrite($file, json_encode($log, JSON_UNESCAPED_UNICODE) . PHP_EOL);
        fclose($file);
    } else {
        echo "打开文件错误";
        exit();
    }

    echo "登录成功。<a href='index.php?c=article_list'>前往文章列表页</a>";
    exit();
} else {
    $log = [
        'action' => 'admin_login',
        'content' => '登录后台失败',
        'time' => date("Y-m-d H:i:s", time()),
        'ip' => $_SERVER['REMOTE_ADDR'],
        'admin_email' => $adminEmail,
    ];
    $file = fopen("./logs/" . date("Y-m-d") . ".txt", 'a+');
    if ($file) {
        fwrite($file, json_encode($log, JSON_UNESCAPED_UNICODE) . PHP_EOL);
        fclose($file);
    } else {
        echo "打开文件错误";
        exit();
    }


    echo "账户或者密码不匹配。<a href='index.php?c=login'>返回登录页</a>";
    exit();
}

//var_dump($articleList);

